<template>
  <van-form @submit="onSubmit" v-if="editUser != null && Object.keys(editUser).length > 0" style="margin-top: 50px">
    <van-cell-group inset v-if="editUser.editKey !== 'avatarUrl' && editUser.editKey !== 'personalProfile' && editUser.editKey !== 'userPassword'">
      <van-field
          v-model="editUser.editValue"
          :name="editUser.editKey"
          :label="editUser.editName"
          :placeholder="`请输入${editUser.editName}`"
          :rules="[{ required: true, message: '请填写用户名' }]"
      />
    </van-cell-group>

    <van-cell-group inset v-else-if="editUser.editKey === 'userPassword'">
      <van-cell>
        <van-field
            v-model="passwordValue"
            :name="editUser.editKey"
            label="旧密码"
            placeholder="请输入原密码"
            :rules="[{ required: true, message: '请输入原密码' }]"
        />
      </van-cell>
      <van-cell>
        <van-field
            v-model="newPasswordValue"
            :name="editUser.editValueNew"
            label="新密码"
            placeholder="请输入新密码"
            :rules="[{ required: true, message: '请输入新密码' }]"
        />
      </van-cell>
    </van-cell-group>


    <van-cell-group inset v-else-if="editUser.editKey === 'personalProfile'">
      <van-field
          v-model="editUser.editValue"
          rows="1"
          autosize
          label="个人简介"
          type="textarea"
          placeholder="请输入个人简介"
      />
    </van-cell-group>

    <van-cell-group  inset v-else>
      <!-- 头像更新 -->
      <van-field name="uploader" label="头像" label-width="4.2em">
        <template #input>
          <van-uploader v-model="imgValue" :after-read="afterRead" max-count="1"></van-uploader>
        </template>
      </van-field>
    </van-cell-group>

    <div style="margin: 16px;" v-if="editUser.editKey !== 'avatarUrl'">
      <van-button round block type="primary" native-type="submit">
        提交
      </van-button>
    </div>

    <div style="margin: 16px;" v-if="editUser.editKey === 'avatarUrl'">
      <van-button round block type="primary" native-type="submit">
        修改头像
      </van-button>
    </div>
  </van-form>



</template>

<script setup lang="ts">
import {useRoute, useRouter} from "vue-router";
import {onMounted, ref} from "vue";
import {uploadImage} from "../api/oss.ts";
import {userStore} from "../stores/user/user.ts";
import {showToast} from "vant";
import {updateUserInfo} from "../api/userApi.ts";

const route = useRoute();
const router = useRouter();
const userStoreAPI = userStore();


//获取路由跳转传过来要编辑的内容！
const editUser = ref({});
const editValueOld = ref();

//密码变量
const passwordValue = ref();
const newPasswordValue = ref();


//头像变量
const imgValue = ref();
const imageFile = ref();

//头像更新的方法
const afterRead = (file) => {
  imageFile.value = file;
  console.log('file',file);
}


//提交给后台修改信息
const onSubmit = async () =>{

  if (editUser.value.editKey == 'userPassword'){
    if (passwordValue.value == ''  || newPasswordValue.value == ''){
      showToast('请填写密码');
      return;
    }else if (passwordValue.value == newPasswordValue.value){
      router.back();
      return;
    }else {
      editUser.value.editValue = passwordValue.value;
      editUser.value.editValueNew = newPasswordValue.value;
    }
  }else {
    if (editValueOld.value == editUser.value.editValue){
      router.back();//回到中心
      return;//一样的不需要改
    }
  }

  //用户头像修改
  if(editUser.value.editKey === 'avatarUrl'){
    const forms = new FormData();
    forms.append('file',imageFile.value.file);
    const res = await uploadImage(forms);
    //直接拿到url进行一个返回
    if (200 == res.code){
      const currentUser = userStoreAPI.getCurrentUser();//更新同步pina
      currentUser.avatarUrl = res.data;
      userStoreAPI.setCurrentUser(currentUser);
      router.back();//回到中心
    }else {
      showToast('修改失败!');
    }
  }else {
    const res = await updateUserInfo(editUser.value);
    if (200 == res.code) {
      //修改成功
      showToast('修改成功');

      //更新同步pina
      const user = await userStoreAPI.getCurrentUser();
      if (editUser.value.editKey === 'phone'){
        user.phone = editUser.value.editValue;
      }else if (editUser.value.editKey === 'personalProfile'){
        user.personalProfile = editUser.value.editValue;
      }else if (editUser.value.editKey === 'username'){
        user.username = editUser.value.editValue;
      }else if (editUser.value.editKey === 'email'){
        user.email = editUser.value.editValue;
      }else if (editUser.value.editKey === 'gender'){
        user.gender = editUser.value.editValue == '男' ? 0 : 1;
      }
      userStoreAPI.setCurrentUser(user);

    } else {
      // 提示出错
      showToast('修改失败!');
    }
    router.back();//回到中心
  }
};

onMounted(async ()=>{
  editUser.value = {
    editId: route.query.id,
    editKey: route.query.key,
    editName : route.query.name,
    editValue: null,
    editValueNew : null
  };
  const user = await userStoreAPI.getCurrentUser();
  if (editUser.value.editKey === 'phone'){
    editUser.value.editValue = user.phone;
    editValueOld.value = user.phone;
  }else if (editUser.value.editKey === 'personalProfile'){
    editUser.value.editValue = user.personalProfile;
    editValueOld.value =user.personalProfile;
  }else if (editUser.value.editKey === 'username'){
    editUser.value.editValue = user.username;
    editValueOld.value = user.username;
  }else if (editUser.value.editKey === 'email'){
    editUser.value.editValue = user.email;
    editValueOld.value = user.email;
  }else if (editUser.value.editKey === 'gender'){
    editUser.value.editValue = user.gender == 0 ? '男' : '女';
    editValueOld.value = user.gender == 0 ? '男' : '女';
  }
  console.log('editValue',editUser.value.editValue);
});




</script>


<style scoped>

</style>